package org.example.service.impl;

import org.example.dao.DeptDao;
import org.example.dao.EmployeeDao;
import org.example.dao.impl.DBUtil;
import org.example.dao.impl.DeptDaoImpl;
import org.example.dao.impl.EmployeeDaoImpl;
import org.example.entity.Employee;
import org.example.entity.EmployeeDTO;
import org.example.service.EmployeeService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class EmployeeServiceImpl implements EmployeeService {

    private DeptDao deptDao = new DeptDaoImpl();
    private EmployeeDao employeeDao = new EmployeeDaoImpl();

    /**
     * 员工部门调动，业务逻辑是根据部门的名称查询到部门的id，再根据部门id和员工的id进行修改
     * @param empId
     * @param deptName
     */
    @Override
    public void transfer(int empId, String deptName) {
        Connection conn = null;
        try {
            conn = DBUtil.getConn();
            conn.setAutoCommit(false); // 开启事务

            int deptId = deptDao.queryDeptIdByName(deptName);
            employeeDao.updateEmployeeDeptId(empId, deptId);

            conn.commit(); // 提交事务
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback(); // 回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            DBUtil.closeConn(conn); // 关闭连接
        }
    }

    @Override
    public void addEmp(Employee employee) {
        employeeDao.addEmp(employee);
    }


    public void saveEmp(Employee employee) {
        employeeDao.addEmp(employee);
    }

    @Override
    public List<EmployeeDTO> getEmployeDTOs() {
        return employeeDao.getEmployeDTOs();
    }

    @Override
    public EmployeeDTO getEmpByName(String empName) {
        return employeeDao.getEmpByName(empName);
    }

    @Override
    public int getDeptIdByName(String deptName) {
        return deptDao.queryDeptIdByName(deptName);
    }

    @Override
    public void deleteEmp(int empId) {
        employeeDao.deleteEmp(empId);
    }

    @Override
    public List<Employee> getAllEmployees() {
        return employeeDao.getAllEmployees();
    }
}